package com.lksoft.bz.tool;

import java.awt.event.MouseEvent;
import java.io.IOException;

import com.lksoft.bz.Bz;
import com.lksoft.bz.command.DrawBeadsCommand;

public class PencilTool extends Tool {
	
	// Undo command
	DrawBeadsCommand command;
	

	public PencilTool(Bz bz, String iconPath, String resourceName) throws IOException {
		super(bz, iconPath, resourceName);
	}

	@Override
	public void mouseClicked(MouseEvent e) {}

	@Override
	public void mouseEntered(MouseEvent e) {}

	@Override
	public void mouseExited(MouseEvent e) {}

	@Override
	public void mousePressed(MouseEvent e) {
		// right-click
		if( e.getButton() != MouseEvent.BUTTON1 ) return;
		
		command = new DrawBeadsCommand(bz, bz.getPaletteBead());
		drawBead(e.getX(), e.getY());
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		// right-click
		if( (e.getModifiersEx() & (MouseEvent.BUTTON2_DOWN_MASK | MouseEvent.BUTTON1_DOWN_MASK)) != MouseEvent.BUTTON1_DOWN_MASK ) {
			return;
		}
				
		drawBead(e.getX(), e.getY());
	}
	

	@Override
	public void mouseReleased(MouseEvent e) {
		// right-click
		if( e.getButton() != MouseEvent.BUTTON1 ) return;
		
		if( bz.getPaletteBead() != null && command.hasAnyChange() ){
			// Register undo command
			bz.addCommand(command);
		}
	}

	@Override
	public void mouseMoved(MouseEvent e) {}
	
	/**
	 * Draw the palette bead at specified coordinates
	 * @param x
	 * @param y
	 */
	private void drawBead(int x, int y){
		// do nothing if no palette set
		if( bz.getPaletteBead() == null ) return;
	
		int beadX = bz.getStitchPanel().xToBeadX(x);
		int beadY = bz.getStitchPanel().yToBeadY(x, y);
		
		// Do nothing if click out of stitch pattern
		if( beadX < 0 || beadY < 0 || beadX >= bz.getStitchPanel().getStitchPattern().getWidth() 
				|| beadY >= bz.getStitchPanel().getStitchPattern().getHeight() ) return;
		
		// Do nothing if original bead and palette bead are the same
		if( bz.getStitchPanel().getStitchPattern().getBead(beadX, beadY) == bz.getPaletteBead().getColor() ) return;
		
		// Register change to undo command
		command.addChange(beadX, beadY, bz.getStitchPanel().getStitchPattern().getBead(beadX, beadY));
		
		if( bz.getStitchPanel().getStitchPattern().setBead(beadX, beadY, bz.getPaletteBead()) ){
			bz.fireUsedBeadsChange();
		}
		bz.redraw();
	}

}
